<template>
  <div>
    <div
      ref="myChart"
      v-show="typeStock.type == 1"
      :style="{ height: border.height + 'px', width: border.width + 'px' }"
      class="myCherts"
      id="myChart"
    ></div>
    <div
      ref="KChart"
      v-show="typeStock.type == 2"
      id="Kline"
      class="kling cb"
      :style="{ height: border.height + 'px', width: border.width + 'px' }"
    ></div>
  </div>
</template>
<script>
import { get_kLine, get_time_line } from "@/assets/js/API/market.js";
import {
  initMOption,
  initKOption,
  initKOptionVolume,
  initKOptionMACD,
} from "@/assets/js/info-line.js";
import { init, dispose, extension } from "klinecharts";
import { checkPointOnSegmentLine } from "klinecharts/lib/mark/graphicHelper"
import { config, configs, getTimezone, judgeColor} from "@/assets/js/kLineConfig.js";
  const rect = {
    name: 'rect',
    totalStep: 3,
    checkMousePointOn: (type, points, mousePoint) => {
      return checkPointOnSegmentLine(points[0], points[1], mousePoint)
    },
    createGraphicDataSource: (step, tpPoint, xyPoints) => {
      if (xyPoints.length === 2) {
        return [
          {
            type: 'line',
            isDraw: false,
            isCheck: true,
            dataSource: [
              [{ ...xyPoints[0] }, { x: xyPoints[1].x, y: xyPoints[0].y }],
              [{ x: xyPoints[1].x, y: xyPoints[0].y }, { ...xyPoints[1] }],
              [{ ...xyPoints[1] }, { x: xyPoints[0].x, y: xyPoints[1].y }],
              [{ x: xyPoints[0].x, y: xyPoints[1].y }, { ...xyPoints[0] }]
            ]
          },
          {
            type: 'polygon',
            isDraw: true,
            isCheck: false,
            style: 'fill',
            dataSource: [
              { ...xyPoints[0] },
              { x: xyPoints[1].x, y: xyPoints[0].y },
              { ...xyPoints[1] },
              { x: xyPoints[0].x, y: xyPoints[1].y }
            ]
          },
          {
            type: 'polygon',
            isDraw: true,
            isCheck: false,
            dataSource: [
              { ...xyPoints[0] },
              { x: xyPoints[1].x, y: xyPoints[0].y },
              { ...xyPoints[1] },
              { x: xyPoints[0].x, y: xyPoints[1].y }
            ]
          }
        ]
      }
      return []
    }
  }
  const circle = {
    name: 'circle',
    totalStep: 3,
    checkMousePointOn: (type, points, mousePoint) => {
      const xDis = Math.abs(points.x - mousePoint.x)
      const yDis = Math.abs(points.y - mousePoint.y)
      const r = Math.sqrt(xDis * xDis + yDis * yDis)
      return Math.abs(r - points.radius) < 3;
    },
    createGraphicDataSource: (step, tpPoint, xyPoints) => {
      if (xyPoints.length === 2) {
        const xDis = Math.abs(xyPoints[0].x - xyPoints[1].x)
        const yDis = Math.abs(xyPoints[0].y - xyPoints[1].y)
        const radius = Math.sqrt(xDis * xDis + yDis * yDis)
        return [
          {
            type: 'arc',
            isDraw: true,
            isCheck: false,
            style: 'fill',
            dataSource: [
              { ...xyPoints[0], radius, startAngle: 0, endAngle: Math.PI * 2 }
            ]
          },
          {
            type: 'arc',
            isDraw: true,
            isCheck: true,
            dataSource: [
              { ...xyPoints[0], radius, startAngle: 0, endAngle: Math.PI * 2 }
            ]
          }
        ];
      }
      return []
    }
  }
export default {
  props: ["typeStock", "echartHeight", "echartWidth"],
  data() {
    return {
      option: {},
      border: {
        height: null,
        width: null,
      },
      echnicalIsList: [
        { name: "volume", id: 0, isShow: true },
        { name: "MACD", id: 1, isShow: true },
      ],
      echnicalItem: true,
      klinecharts: null, // k线初始化
      TimeKlinechart: null, // 分时线
      paneIDs: [], // 副图ID列表
      kTiming: null, // K线定时器
      dataSpace: 0, // K线数据间距
      upColor: "#DD3F3F",
      downColor: "#15A76B"
    };
  },
  created() {
    // var _this = this;
    // if (_this.border.height != null) {
    //   this.timeLines();
    // }
  },
  mounted() {
  },
  beforeDestroy() {
    if(this.kTiming != null) {
      clearInterval(this.kTiming);
      this.kTiming = null;
    }
  },
  methods: {
    echnicalClick(item) {
      var _this = this;
      _this.echnicalIsList[item.id].isShow = !this.echnicalIsList[item.id]
        .isShow;
      _this.echnicalIsList.forEach(function (res, index) {
        if (res.isShow == true) {
          _this.echnicalItem = true;
        }
      });
      setTimeout(function () {
        _this.border.height = _this.echartHeight;
      }, 200);
    },
    //  分时线接口
    async timeLines() {
      var list = [];
      if (this.typeStock.symbol == "" || this.typeStock.symbol == undefined) {
        return false;
      }
      const res = await get_time_line({
        symbol: this.typeStock.symbol,
        period: this.typeStock.coded,
        market: this.typeStock.market,
        securityType: this.typeStock.securityType,
      });
      if (res.code != 1) return this.$message.error(res.msg);
      let len = res.data.list;
      let detail = res.data.detail;
      list["data"] = new Array();
      for (let i = 0; i < len.length; i++) {
        const element = len[i];
        list["data"][i] = new Array();
        list["data"][i].timestamp = parseFloat(element.time) * 1000;
        list["data"][i].close = Number(Number(element.price).toFixed(this.typeStock.precision));
        if(i == 0)
        list["data"][i].open = Number(Number(detail.close).toFixed(this.typeStock.precision));
        else list["data"][i].open = Number(Number(list["data"][i-1].close).toFixed(this.typeStock.precision));
        list["data"][i].low = Number(detail.low);
        list["data"][i].high = Number(detail.high);
        list["data"][i].volume = Number(element.volume);
        list["data"][i].turnover =
          Number(element.volume) * Number(element.price);
        list["data"][i].avgPrice = Number(Number(element.avgPrice).toFixed(this.typeStock.precision));
        // 涨跌额
        list["data"][i].chg = Number(Number(element.price - detail.close).toFixed(this.typeStock.precision));
        list["data"][i].gain = Number(Number(list["data"][i].chg / element.price * 100).toFixed(2));
      }
      if(this.TimeKlinechart != null && this.typeStock.coded == 'day') {
        if(this.typeStock.market == "US"){
          this.TimeKlinechart.setTimezone("America/Toronto");
        }else this.TimeKlinechart.setTimezone("Asia/Shanghai");
        this.TimeKlinechart.applyNewData(list["data"]);
        this.TimeKlinechart.resize();
        this.judgeDataSpace(this.typeStock,list["data"]);
        // 设置分时线与右侧坐标轴距离
        let rightSpace = this.setRightSpace(list["data"].length,this.dataSpace);
        this.TimeKlinechart.setOffsetRightSpace(rightSpace);
      }else this.timeInit(list["data"],this.typeStock);
    },
    // 分时线初始化
    timeInit(data,typeStock) {
      this.$nextTick(function () {
        getTimezone(typeStock);
        this.TimeKlinechart = init(this.$refs.myChart);
        this.TimeKlinechart.createTechnicalIndicator("VOL", false, {
          id: "vol_pane",
          height: 100,
        });
        // 设置精度
        this.TimeKlinechart.setPriceVolumePrecision(typeStock.precision, 4);
        // 添加主图指标
        this.TimeKlinechart.createTechnicalIndicator("AVP",true,{
          id: "candle_pane",
        });
        this.TimeKlinechart.addCustomGraphicMark(rect);
        this.TimeKlinechart.addCustomGraphicMark(circle);
        // 禁止分时的滑动缩放
        this.judgeDataSpace(typeStock,data);
          // 设置K线与右侧坐标轴距离
        let rightSpace = this.setRightSpace(data.length,this.dataSpace);
        this.TimeKlinechart.setOffsetRightSpace(rightSpace);
        judgeColor();
        this.isRedRose();
        // 设置样式配置
        configs.candle.tooltip.labels = [this.$t('info.info_echart.57zd4p13gr80'), this.$t('info.info_echart.57zd4p13hz40'), this.$t('info.info_echart.57zd4p13ib40'), this.$t('info.info_echart.57zd4p13il80'), this.$t('info.info_echart.57zd4p13j5c0'), this.$t('info.info_echart.57zd4p13jjs0'), this.$t('info.info_echart.57zd4p13jt00')]
        configs.technicalIndicator.bar.upColor = this.upColor;
        configs.technicalIndicator.bar.downColor = this.downColor;
        configs.technicalIndicator.circle.upColor = this.upColor;
        configs.technicalIndicator.circle.downColor = this.downColor;
        configs.candle.priceMark.high.color = this.upColor;
        configs.candle.priceMark.low.color = this.downColor;
        this.TimeKlinechart.setStyleOptions(configs);
       // 设置时区
        if(this.typeStock.market == "US")
        {
          this.TimeKlinechart.setTimezone("America/Toronto");
          this.TimeKlinechart.resize();
        } else this.TimeKlinechart.setTimezone("Asia/Shanghai");
        // 筛入数据
        this.TimeKlinechart.applyNewData(data);
      });
    },
    // 根据数组长度设置分时线距离右侧距离使初始线从左边开始
    setRightSpace(length, dataSpace) {
      let KWidth = length * dataSpace;
      let rightSpace = this.border.width - KWidth - 80;
      if(rightSpace <= 0) rightSpace = 40;
      console.log(rightSpace,"距离右侧距离")
      return rightSpace;
    },
    // K线接口
    async Klines(val) {
      let kdata3 = [];
      if (this.typeStock.symbol == "" || this.typeStock.symbol == undefined)
        return false;
      const res = await get_kLine({
        symbol: this.typeStock.symbol,
        market: this.typeStock.market,
        securityType: this.typeStock.securityType,
        period: this.typeStock.coded,
        right: val
      });
      if (res.code != 1) return this.$message.error(res.msg);
      let len = res.data.list;
      for (let i = 0; i < len.length; i++) {
        const element = len[i];
        kdata3[i] = new Array();
        kdata3[i].timestamp = parseFloat(element.time) * 1000;
        kdata3[i].open = Number(element.open);
        kdata3[i].close = Number(element.close);
        kdata3[i].low = Number(element.low);
        kdata3[i].high = Number(element.high);
        kdata3[i].volume = Number(element.volume);
      }
      if(this.klinecharts != null) this.klinecharts.applyNewData(kdata3);
      else this.Kinit(kdata3);
    },
    // k线初始化
    Kinit(kdata3) {
      this.$nextTick(function () {
        this.klinecharts = init(this.$refs.KChart);
        // this.klinecharts = init(document.getElementById("Kline"));
        let paneID = this.klinecharts.createTechnicalIndicator("VOL",false);
        // 将创建的副图保存起来，清除时使用
        this.paneIDs.push(paneID);
        // 设置样式配置
        judgeColor();
        this.isRedRose();
        config.candle.tooltip.labels = [this.$t('info.info_echart.57zd4p13gr80'), this.$t('info.info_echart.57zczfm7c4g0'), this.$t('info.info_echart.57zczfm7cjk0'), this.$t('info.info_echart.57zczfm7cus0'), this.$t('info.info_echart.57zczfm7d600'), this.$t('info.info_echart.57zd4p13jjs0')]
        config.candle.bar.upColor = this.upColor;
        config.candle.bar.downColor = this.downColor;
        config.technicalIndicator.bar.upColor = this.upColor;
        config.technicalIndicator.bar.downColor = this.downColor;
        config.technicalIndicator.circle.upColor = this.upColor;
        config.technicalIndicator.circle.downColor = this.downColor;
        config.candle.priceMark.high.color = this.upColor;
        config.candle.priceMark.low.color = this.downColor;
        if(this.typeStock.market == "US"){
          this.klinecharts.setTimezone("America/Toronto");
        } else this.klinecharts.setTimezone("Asia/Shanghai")
        this.klinecharts.setStyleOptions(config);
        // 设置精度
        this.klinecharts.setPriceVolumePrecision(this.stockMoreInfo.precision, 4);
        this.klinecharts.setLeftMinVisibleBarCount(50);
        this.klinecharts.addCustomGraphicMark(rect);
        this.klinecharts.addCustomGraphicMark(circle);
        //筛入数据
        this.klinecharts.applyNewData(kdata3);
        getTimezone(this.typeStock);
      });
    },
    // 判断涨跌颜色
    isRedRose() {
        if (sessionStorage.getItem("color")=='RedRose') { 
          this.upColor="#DD3F3F";//涨颜色
          this.downColor="#15A76B";//跌颜色
        } else {
          this.upColor="#15A76B";//跌颜色
          this.downColor="#DD3F3F";//涨颜色
        }
    },
    // K线定时器请求30秒一次
    setKTime(val) {
      if(this.kTiming != null) {
        clearInterval(this.kTiming);
        this.kTiming = null;
      }
      if(val == undefined) val = 1;
      this.kTiming = setInterval(()=> {
        if(this.typeStock.type == 2) {
          this.Klines(val);
        }
        else this.timeLines();
      }, 30000)
    },
    // 判断缩放分时图数据间隔与是否禁止缩放
    judgeDataSpace(stock,data) {
      this.TimeKlinechart.setZoomEnabled(false);
      this.TimeKlinechart.setScrollEnabled(false);
      // 判断缩放分时图数据间隔，港股331条，美股391条，沪深241条
      if(stock.type == 1) {
        if(stock.coded == "day") {
          if(stock.market == "HKEX")
          this.dataSpace = Math.floor((this.echartWidth - 100) / 331 * 10) / 10;
          else if(stock.market == "US") 
          this.dataSpace = Math.floor((this.echartWidth - 100) / 391 * 10) / 10;
          else 
          this.dataSpace = Math.floor((this.echartWidth - 100) / 241 * 10) / 10;
        }else this.dataSpace = Math.floor((this.echartWidth - 120) / data.length * 10) / 10;
        this.TimeKlinechart.setDataSpace(this.dataSpace);
      }
      // this.TimeKlinechart.resize();
    },
    // 添加主图辅助线
    addSupple(val) {
      // 清空主图辅助线
      // this.klinecharts.removeTechnicalIndicator();
      // 添加辅助线
      if(!val.flag)
      this.klinecharts.createTechnicalIndicator(val.name,false,{
          id: "candle_pane",
        });
      else this.klinecharts.removeTechnicalIndicator("candle_pane",val.name);
    },
    // 添加副图技术指标
    addTec(val) {
      // 清空当前副图技术指标
      let list = this.paneIDs;
      if(val.flag) {
        // 存在该副图指标时，移除该窗口
        for(let i = 0; i < list.length; i++) {
          let tec = this.klinecharts.getTechnicalIndicatorByPaneId(list[i]);
          // 获取当前副图窗口的技术指标类型
          if(Object.keys(tec)[0] == val.name) {
            this.klinecharts.removeTechnicalIndicator(list[i]);
            // 找到相同类型的副图指标，并删除给i窗口
            this.paneIDs.splice(i,1);
            break;
          }
        };
      }else {
        // 不存在时，添加新的副图窗口
        let paneID = this.klinecharts.createTechnicalIndicator(val.name,false);
          // 将创建的副图保存起来，清除时使用
          this.paneIDs.push(paneID);
        }
    },
    // 添加工具线
    addLine(val,index) {
      if(this.typeStock.type == 1 ) {
        this.TimeKlinechart.createGraphicMark(val, {
          onDrawEnd: ()=> {
            this.$emit("drawEnd");
          },
        });
      }else this.klinecharts.createGraphicMark(val);
    },
    // 取消绘制订阅事件
    deleteTool() {
      if(this.typeStock.type == 2 )
      this.klinecharts.removeGraphicMark();
      else this.TimeKlinechart.removeGraphicMark();
    },
    // K线截屏
    getPictureUrl(){
      let URL;
      if(this.typeStock.type == 2 ) {
        URL = this.klinecharts.getConvertPictureUrl(true, true, "png");
        this.downs(URL);
      }
      else {
        URL = this.TimeKlinechart.getConvertPictureUrl(true, true, "png");
        this.downs(URL);
      }
    },
    // 生成下载链接
    downs(URL) {
      let alink = document.createElement("a");
      alink.href = URL;
      alink.download = "LinkPic"; //图片名
      alink.click();
    }
  },
  destroyed() {
    if (this.klinecharts != null) {
      dispose(document.getElementById("Kline"));
    }
    if (this.TimeKlinechart != null) {
      dispose(document.getElementById("myChart"));
    }
    if(this.setKTime != null) {
      clearInterval(this.setKTime);
      this.setKTime = null;
    }
  },
  watch: {
    typeStock(val, old) {
      var _this = this;
      if (
        old.name == null ||
        val.coded != old.coded ||
        val.type != old.type ||
        val.symbol != old.symbol
      ) {
        if (val.type == 1) {
          if (this.klinecharts != null) {
            dispose(document.getElementById("Kline"));
            this.klinecharts = null;
          }
          _this.timeLines();
          // 1日分时开启定时
          if (val.coded == "day") _this.setKTime();
          _this.border.height = _this.echartHeight;
        } else {
          if (this.TimeKlinechart != null) {
            dispose(document.getElementById("myChart"));
            this.TimeKlinechart = null;
          }
          console.log(this.TimeKlinechart,"K线")
          _this.Klines(1);
          // 1分钟，5分钟开启定时
          if (val.coded == "1min" || val.coded == "5min") _this.setKTime();
          _this.border.height = _this.echartHeight;
        }
      }
    },
    echartHeight(val) {
      this.border.height = val - $(".ChertsBottom").height();
    },
    echartWidth(val) {
      this.border.width = val;
    },
    border: {
      handler(val, old) {
        console.log(val,"改变")
        if (this.typeStock.type == 1) {
          this.timeLines();
        } else {
          this.Klines(1);
        }
      },
      deep: true,
    },
  },
  computed: {
    stockMoreInfo() {
      return this.$store.state.index.stockMoreInfo;
    }
  }
};
</script>
<style lang="less" scoped>
.myCherts {
  overflow: hidden;
}
.ChertsBottom {
  width: 100%;
  .title {
    font-size: 12px;
    color: @fbSix;
    line-height: 30px;
    padding: 0 20px;
    span {
      cursor: pointer;
      margin-left: 15px;
    }
    span.on {
      color: @hoverColor;
    }
  }
}
</style>
